package com.xca.ninedemo.presenter;

import android.content.Context;
import android.util.Log;

import com.xca.ninedemo.contact.TopNewsContact;
import com.xca.ninedemo.entity.TopNews;
import com.xca.ninedemo.service.TopNewsService;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class TopNewsPresenter implements TopNewsContact.TopNewsPresenter {
    private TopNewsContact.TopNewsView mMainView ;
    private Context context ;

    public TopNewsPresenter(TopNewsContact.TopNewsView mMainView, Context context) {
        this.mMainView = mMainView;
        this.context = context;
    }
    @Override
    public void getData(String type) {
        String key = "6cbcdb4250c543fc38a812cce2026a31";
        String url = "http://v.juhe.cn/" ;
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
                .build();
        TopNewsService service = retrofit.create(TopNewsService.class) ;
        service.getData(type , key)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Observer<TopNews>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull TopNews topNews) {
                        if (mMainView != null){
                            mMainView.showData(topNews);
                        }else {
                            Log.e("空指针警告", "mMainView 为 null" );
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        Log.e("错误处理", "数据获取失败: " + e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
}
